home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: tjensen@ix.netcom.com (Ted Jensen)
- Newsgroups: comp.lang.c
- Subject: Re: Pointers to structures
- Date: Wed, 03 Jan 1996 02:27:02 GMT
- Organization: Netcom
- Message-ID: <4ccpgv$qpl@ixnews8.ix.netcom.com>
- References: <4cc9r4$m26@armitage.cyberspace.com>
- Reply-To: tjensen@ix.netcom.com
- NNTP-Posting-Host: pax-ca7-05.ix.netcom.com
- X-NETCOM-Date: Tue Jan 02 6:26:39 PM PST 1996
- X-Newsreader: Forte Free Agent 1.0.82
-
- icarus@loomis (Tel Janin Aellinsar) wrote:
-
- >Berserker Dragon, Knights of the Cosmos icarus@BERKSHIRE.NET
-
- > I'm having trouble using a pointer to a struct. The idea is to
- > have a struct get filled by a function, which gets the address
- > and everything via function(struct type*). Very straightforward.
- > However, if I try to CHANGE anything in the struct, it just goes
- > back when the function is over. So, let's pretend this imaginary
- > structure is what I'm using:
- >
- > struct st1 {
- > char *name;
- > int yadda;
- > };
- >
- > And the function is:
- >
- > fn1(struct st1 *st)
- > {
- > st = (struct st1*)malloc(sizeof(struct st1*));
- > st->name = (char*)malloc(16);
- > strcpy(st->name,"Test");
- > st->yadda = 100;
- > }
-
- Well you have several things wrong here. Since you haven't
- posted a main() I don't know exactly how you go about calling
- your function or what you expect it to return. As things stand,
- you pass the function the value of a pointer. Recall that this
- becomes local to the function and disappears on exiting the
- function. Thus, while you are allocating the space, you have not
- provided a way for the pointer to that space to get returned to
- the calling function.
-
- One way to get the pointer to the allocated memory back to the
- calling program is to write the function as:
-
- struct st1 *fn1(struct st1 *st)
- {
- st = (struct st1 *)malloc(sizeof(struct st1*));
- st->name = (char*)malloc(16);
- strcpy(st->name,"Test");
- st->yadda = 100;
- return st;
- }
-
- Here I have changed the function prototype so that the function
- is expected to return the pointer to the allocated space, and
- added the return statement at the end of the function.
-
- Remember that you need to allocate space for this pointer in the
- calling function before you assign the value returned by this
- function.
-
- For more details on the use of pointers, see my tutorial on same
- which is named PTRTUT01.ZIP and can be found at one of the
- following locations:
-
- http://oak.oakland.edu:8080/SimTel/msdos/c/ptrtut01.zip
-
- ftp.coast.net/SimTel/msdos/c/ptrtut01.zip
-
- Hope this helps!
-
- Ted Jensen Author of PTRTUT01.ZIP
- Redwood City, CA A tutorial on C pointers and Arrays
- tjensen@ix.netcom.com Available via Simtel/msdos/c
-
-